<template>
  <div class="file">
    <div class="header">
      <x-header :left-options="{ backText: '' }">
        <header-title :title="$t('file.dataflowDownload')" />
        <a slot="right" @click="uploadFile">{{ $t('common.upload') }}</a>
      </x-header>
    </div>

    <div class="file-list">
      <divider class="divider-top">{{ $t('file.dataflowNote') }}</divider>
      <group :title="$t('file.httpDownload')">
        <cell
          v-for="(file, index) in files"
          :key="index"
          :title="file.name"
          :value="file.sizeName"
          @click.native="downloadFile(file)"
        >
          <div slot="child" class="icon-download">
            <icon type="download" />
          </div>
        </cell>
      </group>
      <group :gutter="0">
        <div class="tips-box">
          <p>{{ $t('file.browserLookOver') }}</p>
          <p class="tips">{{ $t('file.iosOpenFileTips') }}</p>
        </div>
        <cell
          v-for="(file, index) in files"
          :key="index"
          :title="file.name"
          :value="file.sizeName"
          @click.native="openFileUrl(file.filePath)"
        >
          <div slot="child" class="icon-download">
            <icon type="info" />
          </div>
        </cell>
      </group>
      <group :title="$t('file.uploadBase64')">
        <cell
          :title="$t('file.uploadImageBase64')"
          @click.native="uploadPhotoBase64"
        />
        <cell
          :title="$t('file.uploadFileBase64')"
          @click.native="uploadFileBase64"
        />
      </group>
    </div>
    <div v-transfer-dom>
      <loading :show="isLoading" :text="loadingText" />
    </div>
  </div>
</template>

<script>
import { saveAs } from 'file-saver';
import {
  XHeader,
  Group,
  Cell,
  Icon,
  Loading,
  InlineLoading,
  Divider,
} from 'vux';
import HeaderTitle from '@/components/common/HeaderTitle';
import { getFilesApi, download, fileUpload, base64Upload } from '@/api/file';
import { isIos } from '@/utils/index';

export default {
  components: {
    Icon,
    Group,
    Cell,
    XHeader,
    Loading,
    HeaderTitle,
    InlineLoading,
    Divider,
  },
  data() {
    return {
      files: [],
      isLoading: false,
      client: {}, // 豆豆客户端信息
      loadingText: '',
      host: window.location.host,
      isHttp: document.location.protocol,
      search: {
        page: 1,
        size: 100,
        accountId: null,
      },
    };
  },
  created() {
    this.getClientInfo();
    this.getFiles();
    // 进度通知只需注册一次
    vrv.jssdk.registerProgressNotice({
      success: res => {
        console.log(res, 'registerProgressNotice返回的值');
        this.$nextTick(() => {
          this.loadingText = `${res.progress}%`;
        });
      },
    });
  },
  methods: {
    async getFiles() {
      const res = await getFilesApi(this.search);
      const basePath = `${this.isHttp}//${this.host}`;
      res.data.forEach(item => {
        if (item.staticFilePath) {
          item.filePath = `${basePath}${item.staticFilePath}`;
        }
        item.sizeName = this.getFileSizeText(item.size);
      });
      this.files = res.data;
    },
    getFileSizeText(fileSize) {
      if (!fileSize) {
        return '0B';
      }
      if (fileSize < 1024) {
        return `${fileSize}B`;
      }
      if (fileSize < 1024 * 1024) {
        const text = Math.floor(fileSize / 1024);
        return `${text}KB`;
      }
      if (fileSize < 1024 * 1024 * 1024) {
        const text = Math.floor(fileSize / (1024 * 1024));
        return `${text}MB`;
      }
    },
    uploadFile() {
      vrv.jssdk.getLocalFiles({
        type: 10020,
        rootType: 0,
        upload: true,
        success: async res => {
          console.log(res, 'jssdk返回的值');
          if (res.resultCode === 0) {
            const files = [];
            res.mFilePath.forEach((item, index) => {
              files.push({
                filename: res.mFileName[index],
                fileUrl: item,
              });
            });
            await fileUpload(files);
            this.getFiles();
            this.$vux.toast.show({
              text: this.$t('file.fileUploadSuccessfully'),
              time: 2000,
            });
          }
          this.isLoading = false;
        },
      });
      // FIXME(CFY) pc 取消选择文件没有返回相应状态，在 pc 上传文件暂时不显示进度
      if (this.client.platform && this.client.platform.toLowerCase() !== 'pc') {
        this.isLoading = true;
      }
    },
    async downloadFile(file) {
      if (!file.filePath) {
        this.$vux.toast.show({
          type: 'text',
          width: '20em',
          text: this.$t('file.fileNotSyncSuccessfully'),
          time: 2000,
        });
        return;
      }
      const url = `/api/files/download-url/${file.id}`;
      this.isLoading = true;
      try {
        const res = await download(url, event => {
          const progress = Math.floor((event.loaded / file.size) * 100);
          this.$nextTick(() => {
            this.loadingText = `${progress}%`;
          });
        });

        saveAs(new Blob([res.data]), file.name);
      } catch (error) {
        this.$logan.log(JSON.stringify(error));
      } finally {
        this.isLoading = false;
      }
    },
    openFileUrl(fileUrl) {
      // window.open只能在安卓中打开链接，ios不执行
      if (isIos()) {
        this.$vux.toast.show({
          type: 'text',
          width: '16em',
          text: this.$t('file.noSupportIos'),
        });
        return;
      }
      window.location.href = fileUrl;
    },
    uploadPhotoBase64() {
      vrv.jssdk.getLocalPhotos({
        size: 5,
        upload: false,
        compress: false,
        success: res => {
          console.log(res, 'jssdk返回的值');
          if (res.resultCode !== 0) {
            console.log('取消 base64 上传图片');
            return;
          }
          const names = res.mFileName;
          res.base64.forEach((item, index) => {
            const data = {
              content: item,
              name: names[index],
            };
            const config = {
              onUploadProgress: progressEvent => {
                const progress =
                  ((progressEvent.loaded / progressEvent.total) * 100) | 0;
                this.loadingText = `${progress}%`;
              },
            };
            this.isLoading = true;
            base64Upload(data, config).then(res => {
              this.isLoading = false;
              this.getFiles();
              this.$vux.toast.show({
                text: this.$t('file.fileUploadSuccessfully'),
                time: 2000,
              });
            });
          });
        },
      });
    },
    uploadFileBase64() {
      vrv.jssdk.getLocalFiles({
        size: 5,
        rootType: 0,
        upload: false,
        success: res => {
          console.log(res, 'jssdk返回的值');
          if (res.resultCode !== 0) {
            console.log('取消 base64 上传文件');
            return;
          }
          const names = res.mFileName;
          res.base64.forEach((item, index) => {
            const data = {
              content: item,
              name: names[index],
            };
            const config = {
              onUploadProgress: progressEvent => {
                const progress =
                  ((progressEvent.loaded / progressEvent.total) * 100) | 0;
                this.loadingText = `${progress}%`;
              },
            };
            this.isLoading = true;
            base64Upload(data, config).then(res => {
              this.isLoading = false;
              this.getFiles();
              this.$vux.toast.show({
                text: this.$t('file.fileUploadSuccessfully'),
                time: 2000,
              });
            });
          });
        },
      });
    },
    getClientInfo() {
      vrv.jssdk.getClientInfo({
        success: res => {
          console.log(res, 'Jssdk获取客户端信息');
          this.client = res;
        },
      });
    },
  },
};
</script>

<style lang="less" scoped>
.file {
  height: 100%;
  overflow: hidden;
  .header {
    position: relative;
    height: 45px;
  }
  /deep/ .vux-header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 10;
  }
  .file-list {
    position: relative;
    width: 100%;
    height: calc(100% - 45px);
    margin-top: 60px;
    overflow-y: auto;
    .divider-top {
      margin-top: 15px;
    }
    .icon-download {
      width: 33px;
      margin-left: 10px;
      text-align: center;
    }
  }
  .tips-box {
    background: #f5f5f5;
    padding: 25px 30px 10px 30px;
    font-size: 28px;
    color: #999999;
    .tips {
      color: #F00;
    }
  }
}
</style>
